# coding:utf-8
from const import WECHAT_APPID,WECHAT_APPSECRET,WECHAT_TOKEN,types
from notion import parse_text,hand_add
import hashlib
from fastapi import FastAPI, HTTPException,Request,Depends,BackgroundTasks,Response
import uvicorn

import hashlib
import xmltodict
import time

#封装notion的操作api
import json
import requests

def core(xml_dict):
    content=xml_dict.get("Content")
    user=xml_dict.get("FromUserName")
    if content=="手动记录":


       mode_of_hand[user]={
           "last":0,
           "标题":None,
           "类型":None,
           "金额":None
       }
       text = "开启手动记录模式[回复 退出 退出该模式]，请输入标题："

    elif content=="退出":
        mode_of_hand.pop(user)
        text="退出成功"
    else:

        if user in mode_of_hand.keys():
            if mode_of_hand[user]["last"]==0:
                mode_of_hand[user]["标题"]=content
                text="请选择类型\n"
                for k in types.keys():
                    text+= f'<a href="weixin://bizmsgmenu?msgmenuid=0&msgmenucontent={k}">{k}</a>\n'
                text+="可以直接输入，没有就创建新的标签"
                mode_of_hand[user]["last"]+=1
            elif mode_of_hand[user]["last"]==1:
                mode_of_hand[user]["类型"]=content
                mode_of_hand[user]["last"] += 1
                text="请输入金额【注意支出用负号】"

            elif mode_of_hand[user]["last"]==2:
                mode_of_hand[user]["金额"] = float(content)
                mode_of_hand[user]["last"] += 1
                text=hand_add(mode_of_hand[user]["标题"],mode_of_hand[user]["金额"],mode_of_hand[user]["类型"])
                mode_of_hand[user]["last"] =0



        else:


            text = parse_text(content)
    resp_dict = {
        "xml": {
            "ToUserName": user,
            "FromUserName": xml_dict.get("ToUserName"),
            "CreateTime": int(time.time()),
            "MsgType": "text",
            "Content": text
        }
    }
    # print(xml_dict.get("MsgId"),type(xml_dict.get("MsgId")))
#     token=get_token()
#
#     url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token
#     data={
#     "touser":xml_dict.get("FromUserName"),
#     "msgtype":"text",
#     "text":
#     {
#          "content":"Hello World"
#     }
# }
#     resp = requests.post(url,json=data)
#     print(resp.text)
    result_dict[xml_dict.get("MsgId")]=text
    return text

def get_token():
    url = "https://api.weixin.qq.com/cgi-bin/token?appid=%s&secret=%s&grant_type=client_credential" \
          % (WECHAT_APPID, WECHAT_APPSECRET)
    resp = requests.get(url)
    # print(resp.text)
    data = json.loads(resp.text)
    return data["access_token"]

def verfiy(request:Request):
    signature = request.query_params.get("signature")
    timestamp = request.query_params.get("timestamp")
    nonce = request.query_params.get("nonce")
    return
    # 校验参数
    if not all([signature, timestamp, nonce]):
        raise HTTPException(
            status_code=401,
            detail="不要乱搞哦"
        )

    # 按照微信的流程进行计算签名
    li = [WECHAT_TOKEN, timestamp, nonce]
    # 排序
    li.sort()
    # 拼接字符串
    tmp_str = "".join(li)
    # 进行sha1加密, 得到正确的签名值
    sign = hashlib.sha1(tmp_str.encode()).hexdigest()

    # 将自己计算的签名值与请求的签名参数进行对比，如果相同，则证明请求来自微信服务器
    if signature != sign:
        # 表示请求不是微信发的
        raise HTTPException(
            status_code=401,
            detail="不要乱搞哦"
        )
app=FastAPI(dependencies=[Depends(verfiy)])
@app.get("/wechat")
def sign(request:Request):
    echostr = request.query_params.get("echostr")
    if not echostr:
        raise HTTPException(
            status_code=400,
            detail="不要乱搞哦"
        )
    return Response(content=echostr, media_type="text/html; charset=utf-8")



@app.post("/wechat")
async def wechat(request:Request,task:BackgroundTasks):
    """对接微信公众号服务器"""

    # 表示微信服务器转发消息过来
    xml_str =await request.body()
    if not xml_str:
        raise HTTPException(
            status_code=400,
            detail="不要乱搞哦"
        )

    # 对xml字符串进行解析
    # print(xml_str)
    # print(request.headers)
    xml_dict = xmltodict.parse(xml_str)
    xml_dict = xml_dict.get("xml")
    # print(xml_dict)
    # 提取消息类型
    msg_type = xml_dict.get("MsgType")

    if msg_type == "text":
        # 表示发送的是文本消息
        # 构造返回值，经由微信服务器回复给用户的消息内容
        if xml_dict.get("MsgId") in msg_set:
            for i in range(10):
                if xml_dict.get("MsgId") in result_dict.keys():
                    break
                time.sleep(.5)
        # if xml_dict.get("Content") in result_dict.keys():
            resp_dict = {
                "xml": {
                    "ToUserName": xml_dict.get("FromUserName"),
                    "FromUserName": xml_dict.get("ToUserName"),
                    "CreateTime": int(time.time()),
                    "MsgType": "text",
                    "Content": result_dict[xml_dict.get("MsgId")]
                }
            }
        else:
            msg_set.add(xml_dict.get("MsgId"))
            # task.add_task(core,xml_dict)
            text = core(xml_dict)

            resp_dict = {
                "xml": {
                    "ToUserName": xml_dict.get("FromUserName"),
                    "FromUserName": xml_dict.get("ToUserName"),
                    "CreateTime": int(time.time()),
                    "MsgType": "text",
                    "Content":text

                    # "Content": "正在记录，稍后查询结果...\n可回复本次ID查询结果，ID：{}".format(xml_dict.get("MsgId"))
                }
            }
            # time.sleep(5)
    else:
        resp_dict = {
            "xml": {
                "ToUserName": xml_dict.get("FromUserName"),
                "FromUserName": xml_dict.get("ToUserName"),
                "CreateTime": int(time.time()),
                "MsgType": "text",
                "Content": "请说普通话"
            }
        }

    # 将字典转换为xml字符串
    resp_xml_str = xmltodict.unparse(resp_dict)
    # 返回消息数据给微信服务器
    return Response(content=resp_xml_str, media_type="application/xml")
if __name__ == '__main__':
    # notion=MyNotion()
    mode_of_hand={}
    msg_set=set()
    result_dict=dict()
    uvicorn.run(app,port=80,host="0.0.0.0")
    # app.run(port=80,host="0.0.0.0")